/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.check.checkers;

import cn.ac.iie.di.ban.news.server.check.CheckResult;
import cn.ac.iie.di.ban.news.server.check.Checker;
import java.util.HashSet;

/**
 *
 * @author zwlin
 */
public class Base64Checker implements Checker<String, String> {

	private static final HashSet<Character> BASE64_CHARS;

	static {
		BASE64_CHARS = new HashSet<>();
		for (int i = 0; i < 26; ++i) {
			BASE64_CHARS.add((char) ('A' + i));
			BASE64_CHARS.add((char) ('a' + i));
		}
		for (int i = 0; i < 10; ++i) {
			BASE64_CHARS.add((char) ('0' + i));
		}
		BASE64_CHARS.add('+');
		BASE64_CHARS.add('/');
	}

	/**
	 *
	 * @param src base64 string
	 * @param target not used
	 * @return
	 */
	@Override
	public CheckResult check(String src, String target) {
		char[] cs = src.toCharArray();
		//num of =
		int num = cs.length % 3;
		for (int i = 0; i < num; ++i) {
			if (cs[cs.length - i - 1] != '=') {
				return new CheckResult("Base64 check error. the " + (i + 1) + "th from the last is not '='.");
			}
		}
		//num of regular base 64 chars
		num = cs.length - num;
		for (int i = 0; i < num; ++i) {
			if (!BASE64_CHARS.contains(cs[i])) {
				return new CheckResult("Base64 check error. the " + (i + 1) + "th char is not Base64.");
			}
		}
		return new CheckResult();
	}

}
